package model

import (
	"XSSS_v2/pkg/casbin"
	"fmt"
	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

//全局数据库
var DB *gorm.DB

//初始化数据库
func InitDB() {

	db, err := Open(
		viper.GetString("database.username"),
		viper.GetString("database.password"),
		viper.GetString("database.addr"),
		viper.GetString("database.dbname"),
	)
	if err != nil {
		panic(fmt.Errorf("数据库连接失败err：%s", err.Error()))
	} else {
		DB = db
		fmt.Println("数据库连接成功")
	}

	//创建casbin执行者
	casbin.Casbin()

	//MySQL存储casbin 策略
	casbin.AdminPolicy()
}

func Open(username, password, addr, dbname string) (DB *gorm.DB, err error) {
	//dsn
	dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4&parseTime=%t&loc=%s",
		username,
		password,
		addr,
		dbname,
		true,
		"Local")
	DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	return
}
